﻿@page "/"
@rendermode InteractiveServer
@using DaoHang.Services
@using DaoHang.Models
@using System.Web
@using Microsoft.AspNetCore.Components.Web
@using DaoHang.Components.Shared
@inject IWebsiteService WebsiteService
@inject ICategoryService CategoryService
@inject IUserService UserService
@inject NavigationManager Navigation
@inject IJSRuntime JSRuntime
@inject ISiteSettingsService SiteSettingsService
@inject ILogger<Home> Logger

@* 页面元数据 *@
@if (SiteSettings != null)
{
    <PageTitle>@SiteSettings.SiteTitle</PageTitle>
    <HeadContent>
        @if (!string.IsNullOrEmpty(SiteSettings.SiteDescription))
        {
            <meta name="description" content="@SiteSettings.SiteDescription" />
        }
        @if (!string.IsNullOrEmpty(SiteSettings.SiteKeywords))
        {
            <meta name="keywords" content="@SiteSettings.SiteKeywords" />
        }
        @if (!string.IsNullOrEmpty(SiteSettings.FaviconUrl))
        {
            <link rel="icon" type="image/x-icon" href="@SiteSettings.FaviconUrl" />
        }
    </HeadContent>
}

<div class="hero-background">
    <div class="floating-bubbles">
        @for (int i = 0; i < 15; i++)
        {
            <div class="bubble" style="--delay: @(i * 0.3)s; --size: @(Random.Shared.Next(20, 80))px;"></div>
        }
    </div>
</div>

<div class="main-container">
    <!-- 顶部英雄区域 -->
    <div class="hero-section">
        <div class="hero-content">
            <div class="hero-title">
                <h1 class="main-title">
                    <span class="title-word">精</span>
                    <span class="title-word">选</span>
                    <span class="title-word">导</span>
                    <span class="title-word">航</span>
                </h1>
                <div class="subtitle-container">
                    <p class="subtitle">发现优质内容，探索无限可能</p>
                    <div class="subtitle-line"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
        <div class="search-container">
            <!-- 搜索引擎标签 -->
            <div class="search-engines-tabs">
                <button class="search-engine-tab @(selectedSearchEngine == "百度" ? "active" : "")" @onclick="@(() => selectedSearchEngine = "百度")">
                    <i class="bi bi-search"></i> 百度
                </button>
                <button class="search-engine-tab @(selectedSearchEngine == "Google" ? "active" : "")" @onclick="@(() => selectedSearchEngine = "Google")">
                    <i class="bi bi-google"></i> Google
                </button>
                <button class="search-engine-tab @(selectedSearchEngine == "必应" ? "active" : "")" @onclick="@(() => selectedSearchEngine = "必应")">
                    <i class="bi bi-bing"></i> 必应
                </button>
                <button class="search-engine-tab @(selectedSearchEngine == "GitHub" ? "active" : "")" @onclick="@(() => selectedSearchEngine = "GitHub")">
                    <i class="bi bi-github"></i> GitHub
                </button>
                <button class="search-engine-tab @(selectedSearchEngine == "Gitee" ? "active" : "")" @onclick="@(() => selectedSearchEngine = "Gitee")">
                    <i class="bi bi-git"></i> Gitee
                </button>
            </div>

            <!-- 搜索引擎搜索框 -->
            <div class="search-box">
                <i class="bi bi-search search-icon"></i>
                <input type="text" placeholder="使用搜索引擎搜索..." class="search-input" @bind="searchKeyword" @onkeydown="@SearchKeyDown" />
                @if (!string.IsNullOrEmpty(searchKeyword))
                {
                    <button class="search-clear" @onclick="ClearSearch">
                        <i class="bi bi-x-lg"></i>
                    </button>
                }
                <button class="search-button" @onclick="SearchWithEngine">
                    搜索
                </button>
            </div>

            <!-- 筛选功能 -->
            <div class="filter-section">
                <div class="filter-box">
                    <i class="bi bi-funnel filter-icon"></i>
                    <input type="text" placeholder="筛选页面内网站..." class="filter-input" @bind="filterKeyword" @oninput="OnFilterInput" />
                    @if (!string.IsNullOrEmpty(filterKeyword))
                    {
                        <button class="filter-clear" @onclick="ClearFilter">
                            <i class="bi bi-x-lg"></i>
                        </button>
                    }
                    <span class="filter-label">筛选</span>
                </div>
            </div>
        </div>
    </div>

    <!-- 分类导航 -->
    <div class="categories-section">
        <div class="categories-container">
            <h3 class="section-title">
                <i class="bi bi-grid-3x3-gap-fill"></i>
                网站分类
            </h3>
            <div class="categories-grid">
                <button class="category-chip @(selectedCategoryId == 0 ? "active" : "")"
                        @onclick="() => FilterByCategory(0)">
                    <span class="category-icon">🌐</span>
                    <span class="category-name">全部</span>
                    <span class="category-count">@allWebsites.Count</span>
                </button>
                @foreach (var category in categories.Where(c => 
                    !c.Name.Contains("社交") && 
                    !c.Name.Contains("媒体") && 
                    !c.Name.Contains("新闻") && 
                    !c.Name.Contains("资讯") && 
                    !c.Name.Contains("搜索") && 
                    !c.Name.Contains("引擎")))
                {
                    <button class="category-chip @(selectedCategoryId == category.Id ? "active" : "")"
                            @onclick="() => FilterByCategory(category.Id)">
                        <span class="category-icon">@GetCategoryIcon(category.Name)</span>
                        <span class="category-name">@category.Name</span>
                        <span class="category-count">@websiteCounts.GetValueOrDefault(category.Id, 0)</span>
                    </button>
                }
            </div>
        </div>
    </div>

    <!-- 网站卡片展示区域 -->
    <div class="websites-section">
        <div class="websites-container">
            @if (isLoading)
            {
                <div class="loading-container">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-2">正在加载导航内容...</p>
                </div>
            }
            else if (filteredWebsites.Any())
            {
                <div class="websites-grid">
                    @foreach (var website in filteredWebsites)
                    {
                        <div class="website-card" data-aos="fade-up" @onclick="() => ShowWebsiteDetails(website)">
                            <div class="card-inner">
                                <div class="card-header">
                                    <div class="website-icon">
                                        <WebsiteIcon IconUrl="@website.IconUrl" 
                                                    AltText="@website.Name" 
                                                    CssClass="icon-img" />
                                    </div>
                                    <div class="card-actions">
                                        <span class="category-tag">@website.Category.Name</span>
                                        @if (website.VisitCount > 0)
                                        {
                                            <span class="visit-count">
                                                <i class="bi bi-eye"></i> @website.VisitCount
                                            </span>
                                        }
                                    </div>
                                </div>
                                
                                <div class="card-content">
                                    <h5 class="website-title">@website.Name</h5>
                                    @if (!string.IsNullOrEmpty(website.Description))
                                    {
                                        <p class="website-description" title="@website.Description">
                                            @website.Description
                                        </p>
                                    }
                                    else
                                    {
                                        <p class="website-description text-muted">
                                            暂无描述，点击查看更多信息
                                        </p>
                                    }
                                    <div class="website-url">
                                        <i class="bi bi-link-45deg"></i>
                                        <span>@GetDomainFromUrl(website.Url)</span>
                                    </div>
                                </div>
                                
                                <div class="card-footer">
                                    <a href="@website.Url" target="_blank" class="visit-btn" @onclick="@(() => IncrementVisitCount(website.Id))" @onclick:stopPropagation="true">
                                        <span>立即访问</span>
                                        <i class="bi bi-arrow-right"></i>
                                    </a>
                                </div>
                            </div>
                        </div>
                    }
                </div>
            }
            else
            {
                <div class="empty-state">
                    <div class="empty-icon">
                        <i class="bi bi-search"></i>
                    </div>
                    <h4>暂无相关网站</h4>
                    <p>@(string.IsNullOrEmpty(searchKeyword) ? "当前分类下还没有添加任何网站" : $"没有找到包含 \"{searchKeyword}\" 的网站")</p>
                </div>
            }
        </div>
    </div>

    @if (selectedWebsite != null)
    {
        <div class="modal fade show" id="websiteModal" tabindex="-1" style="display: block; background-color: rgba(0,0,0,0.5);">
            <div class="modal-dialog modal-lg modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <div class="modal-title-section">
                            <div class="website-icon">
                                <WebsiteIcon IconUrl="@selectedWebsite.IconUrl" 
                                            AltText="@selectedWebsite.Name" 
                                            CssClass="modal-icon" />
                            </div>
                            <div>
                                <h5 class="modal-title">@selectedWebsite.Name</h5>
                                <small class="text-muted">@GetDomainFromUrl(selectedWebsite.Url)</small>
                            </div>
                        </div>
                        <button type="button" class="btn-close" @onclick="CloseModal"></button>
                    </div>
                    <div class="modal-body">
                        @if (!string.IsNullOrEmpty(selectedWebsite.Description))
                        {
                            <p class="website-description">@selectedWebsite.Description</p>
                        }
                        <div class="website-details">
                            <div class="detail-item">
                                <label>分类：</label>
                                <span class="badge bg-secondary">@selectedWebsite.Category?.Name</span>
                            </div>
                            @if (selectedWebsite.VisitCount > 0)
                            {
                                <div class="detail-item">
                                    <label>访问量：</label>
                                    <span>@selectedWebsite.VisitCount 次</span>
                                </div>
                            }
                            @if (selectedWebsite.IsRecommended)
                            {
                                <div class="detail-item">
                                    <label>状态：</label>
                                    <span class="badge bg-warning text-dark">
                                        <i class="bi bi-star-fill"></i> 编辑推荐
                                    </span>
                                </div>
                            }
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" @onclick="CloseModal">关闭</button>
                        <a href="@selectedWebsite.Url" target="_blank" class="btn btn-primary" @onclick="() => IncrementVisitCount(selectedWebsite.Id)">
                            <i class="bi bi-box-arrow-up-right"></i> 访问网站
                        </a>
                    </div>
                </div>
            </div>
        </div>
    }
</div>

@code {
    private List<Website> allWebsites = new();
    private List<Website> filteredWebsites = new();
    private List<Category> categories = new();
    private Dictionary<int, int> websiteCounts = new();
    private int selectedCategoryId = 0;
    private bool isLoading = true;
    private string searchKeyword = string.Empty;
    private string selectedSearchEngine = "百度";
    private Website? selectedWebsite;
    private string filterKeyword = string.Empty;
    private Models.SiteSettings? SiteSettings { get; set; }

    /// <summary>
    /// 页面初始化时加载数据
    /// </summary>
    protected override async Task OnInitializedAsync()
    {
        try
        {
            await LoadDataAsync();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"加载数据时发生错误: {ex.Message}");
        }
        finally
        {
            isLoading = false;
        }
    }

    /// <summary>
    /// 加载所有数据，包括网站和分类
    /// </summary>
    private async Task LoadDataAsync()
    {
        // 并行加载数据以提高性能
        var websitesTask = WebsiteService.GetAllWebsitesAsync();
        var categoriesTask = CategoryService.GetAllCategoriesAsync();
        var siteSettingsTask = SiteSettingsService.GetSiteSettingsAsync();

        await Task.WhenAll(websitesTask, categoriesTask, siteSettingsTask);

        allWebsites = await websitesTask;
        categories = await categoriesTask;
        SiteSettings = await siteSettingsTask;
        
        // 计算每个分类的网站数量
        websiteCounts = categories.ToDictionary(
            c => c.Id, 
            c => allWebsites.Count(w => w.CategoryId == c.Id)
        );

        // 默认显示全部分类
        selectedCategoryId = 0;

        // 应用筛选
        ApplyFilters();
    }

    /// <summary>
    /// 根据分类ID筛选网站
    /// </summary>
    /// <param name="categoryId">分类ID</param>
    private void FilterByCategory(int categoryId)
    {
        selectedCategoryId = categoryId;
        ApplyFilters();
    }

    /// <summary>
    /// 搜索输入处理
    /// </summary>
    private void OnSearchInput(ChangeEventArgs e)
    {
        searchKeyword = e.Value?.ToString() ?? string.Empty;
        ApplyFilters();
    }

    /// <summary>
    /// 处理搜索框回车事件
    /// </summary>
    private void SearchKeyDown(KeyboardEventArgs e)
    {
        if (e.Key == "Enter" && !string.IsNullOrWhiteSpace(searchKeyword))
        {
            SearchWithEngine();
        }
    }

    /// <summary>
    /// 使用选定的搜索引擎搜索
    /// </summary>
    private void SearchWithEngine()
    {
        if (string.IsNullOrWhiteSpace(searchKeyword))
            return;

        string searchUrl = selectedSearchEngine switch
        {
            "百度" => $"https://www.baidu.com/s?wd={Uri.EscapeDataString(searchKeyword)}",
            "Google" => $"https://www.google.com/search?q={Uri.EscapeDataString(searchKeyword)}",
            "必应" => $"https://www.bing.com/search?q={Uri.EscapeDataString(searchKeyword)}",
            "GitHub" => $"https://github.com/search?q={Uri.EscapeDataString(searchKeyword)}",
            "Gitee" => $"https://search.gitee.com/?q={Uri.EscapeDataString(searchKeyword)}",
            _ => $"https://www.baidu.com/s?wd={Uri.EscapeDataString(searchKeyword)}"
        };

        JSRuntime.InvokeVoidAsync("open", searchUrl, "_blank");
    }

    /// <summary>
    /// 清除搜索
    /// </summary>
    private void ClearSearch()
    {
        searchKeyword = string.Empty;
    }

    /// <summary>
    /// 应用筛选条件
    /// </summary>
    private void ApplyFilters()
    {
        var websites = allWebsites.AsEnumerable();

        // 按分类筛选
        if (selectedCategoryId != 0)
        {
            websites = websites.Where(w => w.CategoryId == selectedCategoryId);
        }

        // 按筛选关键词筛选
        if (!string.IsNullOrEmpty(filterKeyword))
        {
            websites = websites.Where(w => 
                w.Name.Contains(filterKeyword, StringComparison.OrdinalIgnoreCase) ||
                (w.Description?.Contains(filterKeyword, StringComparison.OrdinalIgnoreCase) ?? false));
        }

        filteredWebsites = websites.ToList();
    }

    /// <summary>
    /// 显示网站详情
    /// </summary>
    private void ShowWebsiteDetails(Website website)
    {
        selectedWebsite = website;
    }

    /// <summary>
    /// 关闭模态框
    /// </summary>
    private void CloseModal()
    {
        selectedWebsite = null;
    }
    
    /// <summary>
    /// 增加网站访问次数
    /// </summary>
    /// <param name="websiteId">网站ID</param>
    private async Task IncrementVisitCount(int websiteId)
    {
        await WebsiteService.IncrementVisitCountAsync(websiteId);
    }

    /// <summary>
    /// 获取分类图标
    /// </summary>
    private string GetCategoryIcon(string categoryName)
    {
        return categoryName.ToLower() switch
        {
            var name when name.Contains("开发") || name.Contains("编程") => "💻",
            var name when name.Contains("在线") && name.Contains("工具") => "🔧",
            var name when name.Contains("学习") || name.Contains("教育") || name.Contains("资源") => "📚",
            var name when name.Contains("云") || name.Contains("服务") => "☁️",
            var name when name.Contains("ai") || name.Contains("人工智能") || name.Contains("智能") => "🤖",
            var name when name.Contains("工具") => "🛠️",
            var name when name.Contains("代码") => "📝",
            var name when name.Contains("设计") => "🎨",
            var name when name.Contains("数据") => "📊",
            var name when name.Contains("测试") => "🧪",
            var name when name.Contains("部署") => "🚀",
            var name when name.Contains("搜索") || name.Contains("引擎") => "🔍",
            var name when name.Contains("社交") || name.Contains("聊天") => "💬",
            var name when name.Contains("购物") || name.Contains("电商") => "🛒",
            var name when name.Contains("视频") || name.Contains("影音") => "🎬",
            var name when name.Contains("音乐") => "🎵",
            var name when name.Contains("新闻") || name.Contains("资讯") => "📰",
            var name when name.Contains("游戏") => "🎮",
            var name when name.Contains("金融") || name.Contains("理财") => "💰",
            var name when name.Contains("旅游") => "✈️",
            var name when name.Contains("美食") => "🍽️",
            var name when name.Contains("健康") || name.Contains("医疗") => "🏥",
            var name when name.Contains("体育") || name.Contains("运动") => "⚽",
            var name when name.Contains("娱乐") => "🎭",
            var name when name.Contains("办公") => "📋",
            var name when name.Contains("生活") => "🏠",
            var name when name.Contains("科技") => "🔬",
            var name when name.Contains("艺术") => "🎨",
            var name when name.Contains("文档") => "📄",
            var name when name.Contains("图片") => "🖼️",
            var name when name.Contains("网络") => "🌐",
            var name when name.Contains("安全") => "🔒",
            var name when name.Contains("通讯") => "📞",
            _ => ""
        };
    }

    /// <summary>
    /// 从URL中提取域名
    /// </summary>
    private string GetDomainFromUrl(string url)
    {
        try
        {
            var uri = new Uri(url);
            return uri.Host;
        }
        catch
        {
            return url;
        }
    }

    /// <summary>
    /// 筛选输入处理
    /// </summary>
    private void OnFilterInput(ChangeEventArgs e)
    {
        filterKeyword = e.Value?.ToString() ?? string.Empty;
        ApplyFilters();
    }

    /// <summary>
    /// 清除筛选
    /// </summary>
    private void ClearFilter()
    {
        filterKeyword = string.Empty;
        ApplyFilters();
    }
}